package com.xiyue.leaspring.datasourceTest;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(locations = {"classpath:spring/spring-jdbc4.xml"})
@RunWith(SpringJUnit4ClassRunner.class)//设置要测试的工具
public class DataSourceTest4 {
	
	private Logger logger = LoggerFactory.getLogger(DataSourceTest4.class);
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
		
	@Test
	public void testDataSource() throws Exception {
		
		KeyHolder keyHolder = new GeneratedKeyHolder();
		String sql = "INSERT INTO news(title,pubdate,note,price,readcount)VALUES(?,?,?,?,?)";
		String title = "阿斯顿";
		Date pubDate = new Date();
		String note = "很好的品牌哈哈";
		double price = 19800.0;
		int readcount = 562100;
		int len = this.jdbcTemplate.update(new PreparedStatementCreator() {
			
			@Override
			public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
				PreparedStatement ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
				ps.setString(1,title);
				ps.setDate(2,new java.sql.Date(pubDate.getTime()));
				ps.setString(3,note);
				ps.setDouble(4,price);
				ps.setInt(5,readcount);
				return ps;
			}
		},keyHolder);//数据更新操作
		this.logger.info("更新行数："+len+"增长后的id"+keyHolder.getKey());
		
	}

}
